package com.tan.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tan.common.domain.user.SysUser;
import com.tan.common.dto.user.UserCreateDto;
import com.tan.common.dto.user.UserUpdateDto;
import com.tan.common.mapper.user.SysUserMapper;
import com.tan.common.mapstruct.user.UserConvert;
import com.tan.common.query.user.UserQuery;
import com.tan.common.vo.user.UserPages;
import com.tan.core.enums.RedisKeyEnum;
import com.tan.core.utils.ExceptionTool;
import com.tan.core.utils.RedissonTool;
import com.tan.core.utils.ThreadPoolTool;
import com.tan.user.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author Tan
 * @since 2025-01-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private RedissonTool redissonTool;

    @Resource
    private ThreadPoolTool threadPoolTool;


    @Override
    public IPage<UserPages> userPages(UserQuery query) {
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery(SysUser.class);
        wrapper.eq(query.getStatus()!=null,SysUser::getStatus,query.getStatus());
        IPage<SysUser> pages = this.baseMapper.selectPage(new Page<>(query.getCurrent(), query.getSize()), wrapper);
        IPage<UserPages> result = new Page<>();
        result.setCurrent(pages.getCurrent());
        result.setTotal(pages.getTotal());
        result.setSize(pages.getSize());
        List<SysUser> users = pages.getRecords();
        List<UserPages> convert = UserConvert.INSTANCE.userToUserPages(users);
        result.setRecords(convert);
        return result;
    }

    @Override
    public void createUser(UserCreateDto dto) {
        SysUser user = UserConvert.INSTANCE.createUserDtoToUser(dto);
        int cont = this.baseMapper.insert(user);
        ExceptionTool.operateSqlError(cont, "创建用户失败");
    }

    @Override
    public void updateUser(UserUpdateDto updateDto) {
        SysUser user = UserConvert.INSTANCE.updateUserDtoToUser(updateDto);
        int count = this.baseMapper.updateById(user);
        ExceptionTool.operateSqlError(count, "修改用户数据失败");
    }

    @Override
    public void delUser(Long userId) {
        int count = this.baseMapper.update(Wrappers.lambdaUpdate(SysUser.class).set(SysUser::getDelFlag, true).eq(SysUser::getId, userId));
        ExceptionTool.operateSqlError(count, "删除用户失败");
        this.removeList(userId);
    }

    @Override
    public List<SysUser> getUsers() {
        String key = RedisKeyEnum.USER_LIST.createKey();
        List<SysUser> users = redissonTool.getObject(key);
        if (ExceptionTool.isEmpty(users)) {
            users = this.baseMapper.selectList(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getDelFlag, false));
            List<SysUser> finalUsers = users;
            if (ExceptionTool.isEmpty(users)) {
                return users;
            }
            threadPoolTool.execute(() -> {
                redissonTool.cacheObjWeek(key, finalUsers);
            });
        }
        return users;
    }

    @Override
    public List<UserPages> getUsersVo() {
        return UserConvert.INSTANCE.userToUserPages(this.getUsers());
    }

    /**
     * 移除缓存
     *
     * @param userId 用户id
     */
    public void removeList(Long userId) {
        threadPoolTool.execute(() -> {
            redissonTool.delCache(RedisKeyEnum.USER_LIST.createKey());
        });
    }

}
